package com.lsl.bhllserver.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lsl.bhllserver.entity.Business;
import com.lsl.bhllserver.entity.Product;
import com.lsl.bhllserver.service.product.AdminProdService;
import com.lsl.bhllserver.service.product.BusProdService;
import com.lsl.bhllserver.service.product.CusProdService;
import com.lsl.bhllserver.service.user.UserManageService;

@RestController
public class ProductController {

    @Autowired
    private AdminProdService adminProdService;

    @Autowired
    private BusProdService busProdService;

    @Autowired
    private CusProdService cusProdService;

    @Autowired 
    private UserManageService userManageService;

    @Autowired
    private OrderController orderController;

    @RequestMapping(path = "/bhll/api/product/create", method = RequestMethod.POST)
    public BoolResponse createProduct(@RequestBody Map<String, String> data) {
        Boolean flag = busProdService.addProd(() -> {
            return new Product(
                null,
                Integer.parseInt(data.get("busid")),
                data.get("prodname"),
                Integer.parseInt(data.get("prodprice")),
                Integer.parseInt(data.get("prodcount")),
                data.get("prodpicture"),
                data.get("prodcaption")
            );
        });
        if (flag) {
            return new BoolResponse("success");
        } else {
            return new BoolResponse("fail");
        }
    }

    @RequestMapping(path = "/bhll/api/product/delete", method = RequestMethod.POST)
    public BoolResponse deleteProduct(@RequestBody Map<String, String> data) {
        boolean flag = false;
        if(data.get("role").equals("admin")) {
            flag = adminProdService.deleteProd(() -> {
                return Integer.parseInt(data.get("prodid"));
            });
        }
        else if(data.get("role").equals("business")) {
            flag = busProdService.deleteProd(() -> {
                return Integer.parseInt(data.get("prodid"));
            });
        }
        else {
            return new BoolResponse("fail");
        }
        if (flag) {
            return new BoolResponse("success");
        } else {
            return new BoolResponse("fail");
        }
    }

    @RequestMapping(path = "/bhll/api/product/edit", method = RequestMethod.POST)
    public BoolResponse editProduct(@RequestBody Map<String, String> data) {
        boolean flag = busProdService.editProd(() -> {
            return new Product(
                Integer.parseInt(data.get("prodid")),
                Integer.parseInt(data.get("busid")),
                data.get("prodName"),
                Integer.parseInt(data.get("prodPrice")),
                Integer.parseInt(data.get("prodCount")),
                data.get("prodPicture"),
                data.get("prodCaption")
            );
        });
        if (flag) {
            return new BoolResponse("success");
        } else {
            return new BoolResponse("fail");
        }
    }

    @RequestMapping(path = "/bhll/api/product/show", method = RequestMethod.GET)
    public ProductList pageShowProd() {
        List<Product> pl = cusProdService.showAllProd();
        List<String> bl = new ArrayList<>();
        for (Product product : pl) {
            bl.add(((Business)userManageService.findUser(
                product.getBusId().toString(),
                "business")).getBusName()
            );
        }
        return new ProductList(pl, bl);
    }

    @RequestMapping(path = "/bhll/api/product/buy", method = RequestMethod.POST)
    public BoolResponse buyProd(@RequestBody Map<String, String> data) {
        boolean flag = orderController.orderCheckOut(data);
        if (flag) {
            return new BoolResponse("success");
        } else {
            return new BoolResponse("fail");
        }
    }

    @RequestMapping(path = "/bhll/api/product/search", method = RequestMethod.POST)
    public ProductList searchProd(@RequestBody Map<String, String> data) {
        //List<String> busIdList = new ArrayList<>();
        //boolean busFoundFlag = false;
        @SuppressWarnings("unchecked")
        List<Business> bl = (List<Business>)userManageService.searchUser(new String[] {
            "",
            data.getOrDefault("busname", ""),
            "",
            "",
        },
        "business");
        List<Product> pl = new ArrayList<>();
        for (Business business : bl) {
            pl.addAll(
                busProdService.searchProduct(new String[] {
                    data.getOrDefault("prodid", ""),
                    data.getOrDefault("prodname", ""),
                    business.getId().toString()
                }
            ));
        }
        List<String> busNameList = new ArrayList<>();
        for (Product product : pl) {
            busNameList.add(((Business)userManageService.findUser(
                product.getBusId().toString(),
                "business")).getBusName()
            );
        }
        return new ProductList(pl, busNameList);
    }

    //新增方法：findProd 用于根据id查找商品
    @RequestMapping(path = "/bhll/api/product/get", method = RequestMethod.POST)
    public ProductWithBusinessInfo findProd(@RequestBody Map<String, String> data) {
        Product product = cusProdService.getProductByID(Integer.parseInt(data.get("prodid")));
        Business business = (Business)userManageService.findUser(
            product.getBusId().toString(),
            "business"
        );
        return new ProductWithBusinessInfo(product, business);
    }

    //新增方法：getMyProd 用于商家获取自己的商品
    @RequestMapping(path = "/bhll/api/product/getMyProd", method = RequestMethod.POST)
    public Object getMyProd(@RequestBody Map<String, String> data) {
        return busProdService.getMyProd(Integer.parseInt(data.get("busid")));
    }

    @RequestMapping(path = "/bhll/api/product/getAll", method = RequestMethod.GET)
    public ProductList getAllProd() {
        List<Product> pl = adminProdService.getAllProd();
        List<String> bl = new ArrayList<>();
        for (Product product : pl) {
            bl.add(((Business)userManageService.findUser(
                product.getBusId().toString(), 
                "business")).getBusName()
            );
        }
        return new ProductList(pl, bl);
    }

    /* =========================================================================================== */

    /*
     * 内部类：返回布尔值的响应类
     */
    class BoolResponse {
        private String flag;

        public BoolResponse(String flag) {
            this.flag = flag;
        }

        public String getFlag() {
            return flag;
        }

        public void setFlag(String flag) {
            this.flag = flag;
        }

    }

    class ProductList {
        private List<Product> pl;
        private List<String> bl;

        public ProductList(List<Product> pl, List<String> bl) {
            this.pl = pl;
            this.bl = bl;
        }

        public List<Product> getPl() {
            return pl;
        }

        public void setPl(List<Product> pl) {
            this.pl = pl;
        }

        public List<String> getBl() {
            return bl;
        }

        public void setBl(List<String> bl) {
            this.bl = bl;
        }
        
    }

    /*
     * 内部类：返回商品信息和商家信息的类
     */
    class ProductWithBusinessInfo {
        private Product product;
        private Business business;
        
        public ProductWithBusinessInfo(Product product, Business bl) {
            this.product = product;
            this.business = bl;
        }

        public Product getProduct() {
            return product;
        }

        public void setProduct(Product product) {
            this.product = product;
        }

        public Business getBusiness() {
            return business;
        }

        public void setBusiness(Business bl) {
            this.business = bl;
        }
    }
}
